from operator import attrgetter
from re import I
from blueking.component.conf import APP_CODE, SECRET_KEY
from django.shortcuts import render
from django.http.response import JsonResponse
from blueking.component.shortcuts import get_client_by_request
from django.conf import settings
import pprint
# Create your views here.

# 获取所有“业务” （内含改为R3的操作）
def all_businesses(client):
    # 获取所有业务(business)
    businesses = client.cc.search_business(bk_app_code=settings.APP_CODE,
                                           bk_app_secret=settings.SECRET_KEY)
    businesses = businesses['data']['info']
    for business in businesses:
        if business['bk_biz_name'] == '蓝鲸':
            print('Found 蓝鲸 业务，改名...')
            update_message = client.cc.update_business(bk_app_code=settings.APP_CODE, bk_app_secret=settings.SECRET_KEY,
                                                       bk_supplier_account=business['bk_supplier_account'], bk_biz_id=business['bk_biz_id'], data={
                                                           'bk_biz_name': 'R3'
                                                       })
    # return [b for b in businesses if b['bk_biz_name']!='蓝鲸' and b['bk_biz_name']!='R3']
    return [b for b in businesses if b['bk_biz_name'] != '蓝鲸' ]

def search_modules(client,biz_id,set_id):
    modules = client.cc.search_module(bk_app_code=settings.APP_CODE,
                                      bk_app_secret=settings.SECRET_KEY,bk_biz_id=biz_id,bk_set_id=set_id)
    return modules

def all_nonsys_hosts(client):
    # 查询主机（排除R3系统业务）$eq | $neq
    hosts = client.cc.search_host(bk_app_code=settings.APP_CODE,
                                  bk_app_secret=settings.SECRET_KEY,
                                  condition= [
                                      {
                                          "bk_obj_id": "host",
                                          "fields": [],
                                          "condition": []
                                      },
                                      {
                                          "bk_obj_id": "module",
                                          "fields": [],
                                          "condition":[]
                                      },
                                      {
                                          "bk_obj_id": "set",
                                          "fields": [],
                                          "condition":[]
                                      },
                                      {
                                          "bk_obj_id": "biz",
                                          "fields": [],
                                          "condition":[
                                            #   {
                                            #       "field": "bk_biz_name",
                                            #       "operator": "$nin",
                                            #       "value": "R3"
                                            #   }
                                          ]
                                      },
                                      {
                                          "bk_obj_id": "object",
                                          "fields": [],
                                          "condition": [
                                            #   {
                                            #       "field": "bk_inst_id",
                                            #       "operator": "$eq",
                                            #       "value": 76
                                            #   }
                                          ]
                                      }
                                  ],
                                  )
    # print(hosts)
    hosts = hosts['data']['info'] if hosts['data'] else []
    # 整合数据
    for h in hosts:
        if h['biz'] and len(h['biz'])>0:   # 有biz定义
            h['bk_biz_id'] = h['biz'][0]['bk_biz_id']
            h['bk_biz_name'] = h['biz'][0]['bk_biz_name']
        
        # if h['set'] and len(h['set'])>0:  # 有集群定义
        #     h['top_module_name'] = h['set'][0]['TopModuleName']
        #     h['bk_set_id'] = h['set'][0]['bk_set_id']
        #     h['bk_set_name'] = h['set'][0]['bk_set_name']

        # if h['module'] and len(h['module'])>0: # 有module定义
        #     h['top_module_name'] = h['module'][0]['TopModuleName']
        #     h['bk_module_id'] = h['module'][0]['bk_module_id']
        #     h['bk_module_name'] = h['module'][0]['bk_module_name']
    # return hosts
    return [h for h in hosts if h['biz'][0]['bk_biz_name'] != 'R3']

# 指定业务的所有集群
def all_sets_in_business(client, business):
    clus = client.cc.search_set(bk_app_code=settings.APP_CODE,
                         bk_app_secret=settings.SECRET_KEY,
                         bk_biz_id=business['bk_biz_id'])
    clus = clus['data']['info']
    return clus

bk_os_type_dict = {
    '1': 'Linux',
    '2': 'Windows',
    '3': 'Aix'
}
bk_alarm_type_dict = {
    'base': '基础',
    'cpu':'CPU',
    'mem': '内存',
    'net':'网络',
    'disk':'磁盘',
    'system_env': '系统',
    'base_alarm':'事件',
    'gse_custom_event': '(字符型)',
    'proc_port':'进程端口',
    'custom':'自定义',
    'keyword':'关键字',
    'process':'进程',
    'selfscript':'脚本',
    'uptimecheck': '服务拨测',
    'apache': 'apache',
    'mysql': 'mysql',
    'nginx': 'nginx',
    'redis': 'redis','tomcat':'tomcat',
    'ad':'ad','ceph':'ceph',
    'consul':'consul',
    'elastic':'elastic',
    'exchange2010':'exchange2010',
    'haproxy':'haproxy',
    'iis':'iis',
    'jmx':'jmx',
    'kafka':'kafka',
    'memcache':'memcache',
    'mongodb':'mongodb',
    'mssql':'mssql',
    'oracle':'oracle',
    'rabbitmq':'rabbitmq',
    'weblogic':'weblogic',
    'zookeeper':'zookeeper'
}

bk_alarm_level_dict = {
    '1': '致命',
    '2': '预警',
    '3': '提醒'
}

from collections import defaultdict
def _group_hosts(hosts):
    grouped_hosts = defaultdict(int)
    for os_type,os_name in bk_os_type_dict.items():
        grouped_hosts[os_name] = 0
    for host in hosts:
        print(' Dealing host :',host['host']['bk_host_name'])
        grouped_hosts['全部服务器'] += 1
        grouped_hosts[bk_os_type_dict.get(host['host']['bk_os_type'], '未知OS')] += 1
        if host['set'] and len(host['set']) > 0:  # 有module定义
            for m in host['set']:
                grouped_hosts[m['bk_set_name']] += 1
    print('====== digital flop ======')
    pprint.pprint(grouped_hosts)
    return grouped_hosts


# json webapi
def digital_flop_data(request):
    client = get_client_by_request(request=request)
    hosts = all_nonsys_hosts(client)
    grouped_hosts = _group_hosts(hosts)
    return JsonResponse({"grouped": grouped_hosts})

import datetime
def alarms_recent(request):
    client = get_client_by_request(request=request)
    now = datetime.datetime.now(tz=datetime.timezone(datetime.timedelta(hours=8)))
    one_day_delta = datetime.timedelta(days=1)
    print("SINCE:",now-one_day_delta)
    
    since = str(now-one_day_delta)
    since = since[:19]
    print(' source_time_from :', since)
    alarms = client.cc.list_alarm_instance(bk_app_code=settings.APP_CODE,
                                           bk_app_secret=settings.SECRET_KEY, 
                                           source_time__gte = since,page_size=200
                                           )
    print(' alarms: -------')
    pprint.pprint(alarms)
    alarms = alarms['data'] if alarms['data'] else []
    alarms = [{
        'message': a['alarm_content']['title'],
        'alarm_type': bk_alarm_type_dict[a['alarm_type']],
        'level': bk_alarm_level_dict[str(a['level'])],
        'source_time': a['source_time'],
        'status': a['status']
    } for a in alarms]
    print('======    alarms ========')
    pprint.pprint(alarms)
    alarms = sorted(alarms, key=lambda a: a['source_time'], reverse=True)
    alarms = alarms[:45]
    return JsonResponse({'recent_alarms': alarms})

def alarms_stats(request):
    client = get_client_by_request(request=request)
    alarms = client.cc.list_alarm_instance(bk_app_code=settings.APP_CODE,
                                           bk_app_secret=settings.SECRET_KEY)
    alarms = alarms['data'] if alarms['data'] else []
    # exclude sys biz(R3|BlueKing)
    # alarms = [a for a in alarms if a['bk_biz_id']!=2  ]
    
    type_stats = defaultdict(int)
    for t,v in bk_alarm_type_dict.items(): 
        type_stats[v] = 0
    level_stats = defaultdict(int)
    for l,lv in bk_alarm_level_dict.items():
        level_stats[lv]=0
    status_stats = defaultdict(int)

    module_stats = defaultdict(int)
    
    for a in alarms:
        type_stats[bk_alarm_type_dict.get(a['alarm_type'],'未知类型')] += 1
        level_stats[bk_alarm_level_dict.get(str(a['level']),'未知级别')] += 1
        status_stats[a['status']] += 1
        # 有些 监控 （PING不可达） 没有模块信息，用 source_name 代替
        if a['alarm_dimension'] and '模块' in a['alarm_dimension']:
            for m in a['alarm_dimension']['模块']:
                module_stats[m] += 1
        else:
            module_stats[a['alarm_content']['source_name']] += 1
    return JsonResponse({"type_stats": type_stats, "level_stats":level_stats, "status_stats": status_stats, "module_stats": module_stats})

def agent_status(request):
    client = get_client_by_request(request=request)
    hosts = all_nonsys_hosts(client=client)
    p_hosts = [{
        'bk_cloud_id': h['host']['bk_cloud_id'][0]['id'],
        'ip': h['host']['bk_host_innerip']
    } for h in hosts]
    agents = client.gse.get_agent_status(bk_app_code=settings.APP_CODE,
                                bk_app_secret=settings.SECRET_KEY, hosts = p_hosts, bk_supplier_account=0)
    agents = agents['data']
    print('========= agent status ==========')
    pprint.pprint(agents)
    agents = agents.values()
    cnt = 0
    for a in agents:
        if a['bk_agent_alive'] == 1:
            cnt += 1
    return JsonResponse({'agent_status': {'all': len(agents), 'alive': cnt}})

def cpu_performance(client, biz_id=2):
    
    data = client.cc.query_data(bk_app_code=settings.APP_CODE,
                         bk_app_secret=settings.SECRET_KEY, 
                         sql='select avg(usage) as cpu_usage from {}_system_cpu_summary where time >= "5m" group by ip order by time desc limit 5'.format(biz_id))
    print('------------ cpu data -----------',biz_id)
    
    pprint.pprint(data)
    return data['data']['list'] if 'code' in data and data['code'] == '0' else []

def mem_performance(client, biz_id=2, ips="'10.0.0.23'"):
    command = ' or '.join(["ip = '" + ip + "'" for ip in ips])
    data = client.cc.query_data(bk_app_code=settings.APP_CODE,
                                bk_app_secret=settings.SECRET_KEY,
                                sql='select avg(pct_used) as mem_usage from {}_system_mem where time >= "5m" and ({}) group by ip order by time desc limit 5'.format(biz_id,command))
    print('------------ mem data ------------', biz_id, '\n',
          'select avg(pct_used) as mem_usage from {}_system_mem where time >= "5m" and ({}) group by ip order by time desc limit 5'.format(biz_id, command))
    pprint.pprint(data)
    return data['data']['list'] if 'code' in data and data['code'] == '0' else []

def io_performance(client, biz_id=2, ips="'10.0.0.23'"):
    command = ' or '.join(["ip = '"+ ip + "'" for ip in ips])
    data = client.cc.query_data(bk_app_code=settings.APP_CODE,
                                bk_app_secret=settings.SECRET_KEY,
                                sql='select avg(util) as io_usage from {}_system_io where time >= "5m" and ({}) group by ip order by time desc limit 5'.format(biz_id, command))
    print('------------ io data -----------', biz_id, '\n',
          'select avg(util) as io_usage from {}_system_io where time >= "5m" and ({}) group by ip order by time desc limit 5'.format(
              biz_id, command))
    pprint.pprint(data)
    return data['data']['list'] if 'code' in data and data['code'] == '0' else []

# api view function
def cpu_perfs(request):
    client = get_client_by_request(request=request)
    bizs = all_businesses(client)
    cpu_datas = []
    mem_datas = []
    io_datas = []
    for biz in bizs:
        _cpu_data = cpu_performance(client, biz_id=biz['bk_biz_id'])
        cpu_datas = cpu_datas + _cpu_data
        print('===== cpu_performance ok =======',biz['bk_biz_id'])
        pprint.pprint(_cpu_data)
        if len(_cpu_data) == 0:
            continue
        ips = [c['ip'] for c in _cpu_data]
        
        # ips = "'"+ips+"'"
        mem_datas = mem_datas + mem_performance(client,biz_id=biz['bk_biz_id'],ips=ips)
        io_datas = io_datas + io_performance(client,biz_id=biz['bk_biz_id'],ips=ips)
    cpu_datas=sorted(cpu_datas, key=lambda c : c['cpu_usage'], reverse=True)
    mem_datas=sorted(mem_datas, key=lambda m: m['mem_usage'], reverse=True)
    io_datas=sorted(io_datas, key=lambda i: i['io_usage'], reverse=True)

    return JsonResponse({'cpu_perfs': cpu_datas[:5], 'mem_perfs':mem_datas[:15], 'io_perfs': io_datas[:15]})

# test view function.s
def hello(request):
    client = get_client_by_request(request=request)

    # 获取所有业务(business)
    businesses = all_businesses(client)

    # hosts = all_nonsys_hosts(client)
    # # print(hosts)

    
    # bk_sets = {}
    # for business in businesses:
    #     # 获取 业务 的所有集群
    #     bk_sets[business['bk_biz_id']] = all_sets_in_business(client,business=business)
        
    #     # pass
    # # print(bk_sets)

    # modules = []
    # for biz_id,ss in bk_sets.items():
    #     # print("biz_id:",biz_id)
    #     # print("VALUE:",ss)
    #     for s in ss:
    #         m = search_modules(client=client,biz_id=biz_id,set_id=s['bk_set_id'])
    #         modules += m['data']['info'] if m['data'] else []
    
    # components_alarms = client.cc.list_component_instance(bk_app_code=settings.APP_CODE,
    #                                                     bk_app_secret=settings.SECRET_KEY)
    # alarms = client.cc.list_alarm_instance(bk_app_code=settings.APP_CODE,
    #                                            bk_app_secret=settings.SECRET_KEY)

    # print('Before Group #',len(hosts))
    # grouped_hosts = _group_hosts(hosts)
    # import pprint
    # print('='*100)
    # # pprint.pprint(components_alarms['data']['info'][:10])
    # print('='*100)
    # # pprint.pprint(alarms)

    # # cpu_perfs = cpu_performance(request)
    return JsonResponse({"businesses": businesses})
